//
//  HICollectionView.swift
//  Health_Infomation
//
//  Created by 林帆 on 2017/8/19.
//  Copyright © 2017年 林帆. All rights reserved.
//

import UIKit

@objc protocol HISearchCollectionCellDelegate {
    func HISearchCollectionCellEdit(title: String)
}

class HISearchCollectionView: UIView {
    
    var DataAry : Array<Any> = []
    var removeItemTag : NSInteger = 0
    weak var HISearchCollCellDelegate : HISearchCollectionCellDelegate? = nil
    lazy var MainCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout())
    lazy var EditedBtn = UIButton()
    lazy var CancelBtn = UIButton()
    
    convenience init(DataArray: Array<Any>) {
        self.init()
        self.DataAry = DataArray
        ConfigUI()
    }
    
    func ConfigUI () {
        // FlowLayout
        let FlowLayout = UICollectionViewFlowLayout()
        FlowLayout.minimumLineSpacing = 10
        FlowLayout.minimumInteritemSpacing = 20
        FlowLayout.itemSize = CGSize.init(width: 30, height: 34)        // 子视图
        FlowLayout.sectionInset = UIEdgeInsetsMake(12, 12, 12, 12)        // 边缘距离
        
        MainCollectionView.delegate = self
        MainCollectionView.dataSource = self
        MainCollectionView.register(HISearchCollectionCell.self, forCellWithReuseIdentifier: "HISearchCollectionCell")
        MainCollectionView.register(HISearchCollectionHeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HISearchCollectionHeadView")
        MainCollectionView.register(HISearchCollectionHeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "HISearchCollectionHeadView")
        MainCollectionView.backgroundColor = kRGBColorFromHex(rgbValue: 0xfafafa)
        MainCollectionView.collectionViewLayout = FlowLayout
        self.addSubview(MainCollectionView)
        MainCollectionView.snp.makeConstraints({ (make) in
            make.edges.equalTo(self)
        })
    }

    func clearClick() {
        if (DataAry[0] as! [String]).count < 1 {
            return
        }
        let alertController = UIAlertController(title: "清空历史记录", message: "是否确认清空", preferredStyle: .alert)
        let cancelAction1 = UIAlertAction(title: "确定", style: .default, handler: { (UIAlertAction) in
            if self.DataAry.count > 1 {
                var Array = self.DataAry[0] as! [String]
                Array.removeAll()
                self.DataAry[0] = Array
                self.MainCollectionView.reloadData()
            }
        })
        let cancelAction2 = UIAlertAction(title: "取消", style: .cancel, handler: { (UIAlertAction) in
            print("dd")
        })
        alertController.addAction(cancelAction1)
        alertController.addAction(cancelAction2)
        UIViewController.getCurrentController()?.present(alertController, animated: true, completion: nil)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    deinit {
        print("本宝宝被销毁啦1")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension HISearchCollectionView : UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout {
    
    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    //返回多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (DataAry[section] as AnyObject).count
    }
    
    // 计算宽高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let textMaxSize = CGSize(width: kScreenWitdh, height: CGFloat(MAXFLOAT))
        let resultSize : CGSize
        resultSize = fftextSize(text: (DataAry[indexPath.section] as! Array)[indexPath.row], font: UIFont.systemFont(ofSize: 15), maxSize: textMaxSize)
        if indexPath.section == 0 {
            return CGSize(width: resultSize.width + 18, height: 34)
        } else {
            return CGSize(width: resultSize.width + 38, height: 34)
        }
    }
    
    //返回自定义的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HISearchCollectionCell", for: indexPath) as! HISearchCollectionCell
        cell.titleLabel.frame =  cell.bounds
        cell.titleLabel.textColor = kRGBColorFromHex(rgbValue: 0x333333) //推荐 回退设置
        cell.titleLabel.text = (DataAry[indexPath.section] as! Array)[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        HISearchCollCellDelegate?.HISearchCollectionCellEdit(title: (DataAry[indexPath.section] as! [String])[indexPath.row])
    }
    
    //这个是设定header和footer的方法，根据kind不同进行不同的判断即可
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let TextLabelAry = ["历史搜索","热门搜索"]
        
        if kind == UICollectionElementKindSectionHeader {
            let HISearchCollectionHeadView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HISearchCollectionHeadView", for: indexPath) as! HISearchCollectionHeadView
            
            HISearchCollectionHeadView.titleLabel.text = TextLabelAry[indexPath.section]
            HISearchCollectionHeadView.titleLabel.frame = CGRect(x: 12, y: 10, width: 80, height: 20)
            HISearchCollectionHeadView.titleLabel.textAlignment = NSTextAlignment.left
            HISearchCollectionHeadView.addSubview(HISearchCollectionHeadView.titleLabel)
            
            if indexPath.section == 0{
                EditedBtn.setImage(UIImage(named: "清空"), for: .normal)
                HISearchCollectionHeadView.addSubview(EditedBtn)
                EditedBtn.addTarget(self, action: #selector(clearClick), for: .touchUpInside)
                EditedBtn.snp.makeConstraints({ (make) in
                    make.right.equalTo(HISearchCollectionHeadView).offset(-12)
                    make.top.equalTo(HISearchCollectionHeadView).offset(10)
                    make.height.equalTo(16)
                    make.width.equalTo(14)
                })
            }
            return HISearchCollectionHeadView
        }
        else{
            let HISearchCollectionHeadView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "HISearchCollectionHeadView", for: indexPath)
            return HISearchCollectionHeadView
        }
    }
    
    //header高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: UIScreen.main.bounds.size.width, height: 40.0)
    }
    //footer高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: UIScreen.main.bounds.size.width, height: 25.0)
    }
}

/// ----------------- HISearchCollectionCell

class HISearchCollectionCell: UICollectionViewCell {
    
    lazy var titleLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.layer.cornerRadius = 8
        self.layer.borderWidth = 0.5
        self.layer.borderColor = kRGBColorFromHex(rgbValue: 0xeeeeee).cgColor
        
        self.backgroundColor = kRGBColorFromHex(rgbValue: 0xffffff)
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.textAlignment = NSTextAlignment.center
        self.contentView.addSubview(titleLabel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

/// -----------------  HISearchCollectionHeadView
class HISearchCollectionHeadView: UICollectionReusableView {
    
    lazy var titleLabel = UILabel(ffText: "", fontSize: 16, textColor: kRGBColorFromHex(rgbValue: 0x333333))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

/// ----------------- HISearchCollectionFootView
class HISearchCollectionFootView: UICollectionReusableView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = kRGBColorFromHex(rgbValue: 0xfafafa)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


